from django.shortcuts import render
from django.http import JsonResponse
from django.conf import settings
from user.models import User, VSession, WarZone, Company
from storehouse.models import Storehouse, StorehouseConnect
from log.models import UserLog
from user.dataCheck import DataCheck
from urllib.request import urlopen
from django.db.models import Q
import pdb, os, requests
import logging
import socket
import time
from software.views.view_download import download
from conf.sysConfig import config

tmpDir = os.path.join(config["dataDir"], config["tmpDir"])
logger_request = logging.getLogger("django.request")
datacheck = DataCheck()


def getStorehouseInfo(request, *args, **kwargs):
    """
        url    : /storehouse/msgshow/
        method : POST

    :param request:
               token: data.token, // 用户的秘钥


    :return:
              'code': null, // 标志返回状态、0：成功 1：失败
              'msg': null, // 返回消息
              'storehouseName':null,//仓库名称
              'warZone':null,//所属战区
              'warZoneId':null,//所属战区Id
              'company':null,//所属单位
              'companyId':null,//所属单位Id
              'linkName':null,//联系人
              'linkPhone':null,//联系电话
              'createtime':null,//创建时间
              'storehouseDetails':null,//仓库描述
              'storeIP':null,//节点ip，无则空
              'connectIP':null,//接入主节点IP
              'isMasterStore':null,//节点当前类型，0：子节点，1：主节点
              'connectState':null,//是否连接，0：未连接，1已连接,2:已拒绝             
    """
    form = request.checkForm
    requestParam = form.cleaned_data
    # pdb.set_trace()    
    logger_request.info(requestParam)
    # pdb.set_trace()

    user = datacheck.getUser(requestParam['token'])
    userType = user.userType

    if userType == '2':
        storehouseList = Storehouse.objects.filter(user=user)
        storehouse = storehouseList[0]
        # pdb.set_trace()
        # myname = socket.getfqdn(socket.gethostname())
        # myaddr = socket.gethostbyname(myname)

        # x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        # if x_forwarded_for:
        #     ip = x_forwarded_for.split(',')[0]  # 所以这里是真实的ip
        # else:
        #     ip = request.META.get('REMOTE_ADDR')
        # s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
        # s.connect(('10.0.0.1',8080))
        # ip= s.getsockname()[0]
        # pdb.set_trace()
        try:
            # ip = requests.get('http://ifconfig.me/ip', timeout=1).text.strip()
            ip = config["ownIp"]
            port = config["ownPort"]
        except:
            ip = "127.0.0.1"
            port = "80"
        # port = request.META['SERVER_PORT']

        storehouse.storeIP = ip
        storehouse.storePort = port
        storehouse.save()
    else:
        data = {
            'code': 1,
            'msg': 'userType error',
        }
        logger_request.info(data)
        return JsonResponse(data)

    data = {
        "code": 0,
        "msg": "success",
        "storehouseId": storehouse.id,
        "storehouseName": storehouse.storehouseName,
        "storehouseDetails": storehouse.storehouseDetails,
        "createtime": storehouse.createTime.strftime('%Y-%m-%d %H:%M:%S'),
        "isMasterStore": storehouse.storeIPType,
        "storeIP": storehouse.storeIP,
        "connectState": storehouse.connectState,
        "connectIP": storehouse.connectIP,
        "warZone": storehouse.warZone.name,
        "warZoneId": storehouse.warZone.id,
        "company": storehouse.company.name,
        "companyId": storehouse.company.id,
        "linkName": storehouse.linkName,
        "linkPhone": storehouse.linkPhone,
        'storePort': storehouse.storePort,
        'connectPort': storehouse.connectPort,
    }
    logger_request.info(data)
    return JsonResponse(data)


def changeStorehouseInfo(request, *args, **kwargs):
    """
        url    : /user/msgchange/
        method : POST

    :param request:
               token: data.token, // 用户的秘钥
                storehouseId:data.storehouseId,//仓库id
                storehouseName:data.storehouseName,//仓库名称
                warZone:data.warZone,//所属战区
                company:data.company,//所属单位
                name:data.name,//联系人
                phone:data.phone,//联系电话
                storehouseDetails:data.storehouseDetails,//仓库描述

    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息

    """
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)

    user = datacheck.getUser(requestParam['token'])
    userType = user.userType

    if userType == '2':
        storehouse = Storehouse.objects.get(pk=requestParam['storehouseId'])
        warZone = WarZone.objects.get(pk=requestParam['warZoneId'])
        company = Company.objects.get(pk=requestParam['companyId'])

        # pdb.set_trace()

        storehouse.storehouseName = requestParam['storehouseName']
        storehouse.storehouseDetails = requestParam['storehouseDetails']
        storehouse.linkName = requestParam['linkName']
        storehouse.linkPhone = requestParam['linkPhone']
        storehouse.warZone = warZone
        storehouse.company = company
        storehouse.save()
    else:
        data = {
            'code': 1,
            'msg': 'userType error',
        }
        logger_request.info(data)
        return JsonResponse(data)

    data = {
        "code": 0,
        "msg": "success",
    }
    logger_request.info(data)
    return JsonResponse(data)


def getSubStoreList(request, *args, **kwargs):
    """
        url    : /storehouse/list/
        method : POST

    :param request:
               token: data.token, // 用户的秘钥
               page: data.page,
               maxItem: data.maxItem

    :return:
                'code': null, // 标志返回状态、0：成功 1：失败
                'msg': null, // 返回消息
                'totalNum': null, // 总条数
                'storehouselist':[{
                    'storehouseId':null,//仓库id
                    'storehouseName':null,//仓库名称
                    'warZone':null,//所属战区
                    'company':null,//所属单位
                    'applytime':null,//仓库申请时间
                    'storehouseState':null,//仓库状态 0：已开启，1：已关闭，
                    'runstate':null,//0:在线，1:离线
                    'connectstate':null,//0:已连接，1:已拒绝，2未连接
                }]
    """

    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)

    user = datacheck.getUser(requestParam['token'])
    userType = user.userType

    if userType == '2':
        masterStorehouseList = Storehouse.objects.filter(user=user)
        masterStorehouse = masterStorehouseList[0]
        if masterStorehouse.isMasterStore == True:
            storeConnectList = StorehouseConnect.objects.filter(masterStorehouseId=masterStorehouse.id).filter(
                ~Q(connectState='3'))
            if storeConnectList.exists():
                storeConnectLists = []

                storehouseLists = []

                for storeConnect in storeConnectList:
                    storehouseList = Storehouse.objects.filter(pk=storeConnect.subStorehouseId)

                    for storehouse in storehouseList:
                        storehouseList = {
                            'storehouseId': storehouse.id,
                            'storehouseName': storehouse.storehouseName,
                            'storeIP': storehouse.storeIP,
                            'warZone': storehouse.warZone.name,
                            'company': storehouse.company.name,
                            'storehouseState': storehouse.storehouseState,
                            'runstate': storehouse.runState,
                            'connectstate': storehouse.connectState,
                            'applytime': storeConnect.applyTime.strftime('%Y-%m-%d %H:%M:%S'),
                        }
                        storehouseLists.append(storehouseList)

                    totalNum = len(storehouseLists)
                    result = storehouseLists[
                             min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
                                                                                                      requestParam[
                                                                                                          'page'] *
                                                                                                      requestParam[
                                                                                                          'maxItem'])]

            else:
                data = {
                    "code": 0,
                    "msg": "success",
                    "totalNum": 0,
                    "storehouselist": [],
                }
                logger_request.info(data)
                return JsonResponse(data)

        else:
            data = {
                'code': 0,
                'msg': 'master error',
                "totalNum": 0,
                "storehouselist": [],
            }
            logger_request.info(data)
            return JsonResponse(data)
    else:
        data = {
            'code': 0,
            'msg': 'userType error',
            "totalNum": 0,
            "storehouselist": [],
        }
        logger_request.info(data)
        return JsonResponse(data)

    data = {
        "code": 0,
        "msg": "success",
        "totalNum": totalNum,
        "storehouselist": result,
    }
    logger_request.info(data)
    return JsonResponse(data)


def subStorehouseMsg(request, *args, **kwargs):
    """
        url    : /storehouse/subInfo/
        method : POST

    :param request: 
               token: data.token, // 用户的秘钥
                storehouseId: data.storehouseId, // 仓库Id 

    :return:
              'code': null, // 标志返回状态、0：成功 1：失败
              'msg': null, // 返回消息
              'storehouseName':null,//仓库名称
              'warZone':null,//所属战区
              'company':null,//所属单位
              'linkName':null,//联系人
              'linkPhone':null,//联系电话
              'createtime':null,//创建时间
              'storehouseDetails':null,//仓库描述
              'storeIP':null,//节点ip，无则空
              'storehouseState':null,//仓库状态 0：已开启，1：已关闭，
              'runstate':null,//0:在线，1:离线          
    """
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    # pdb.set_trace()

    user = datacheck.getUser(requestParam['token'])
    userType = user.userType

    if userType == '2':
        masterstore = Storehouse.objects.filter(user=user).first()
        storehouse = Storehouse.objects.get(pk=requestParam['storehouseId'])
        storeconnect = StorehouseConnect.objects.filter(subStorehouseId=requestParam['storehouseId'],
                                                        masterStorehouseId=masterstore.id).first()
    else:
        data = {
            'code': 1,
            'msg': 'userType error',
        }
        logger_request.info(data)
        return JsonResponse(data)
    # pdb.set_trace()
    data = {
        "code": 0,
        "msg": "success",
        "storehouseName": storehouse.storehouseName,
        "storehouseDetails": storehouse.storehouseDetails,
        "createtime": storehouse.createTime.strftime('%Y-%m-%d %H:%M:%S'),
        "storeIP": storehouse.storeIP,
        "storePort": storehouse.storePort,
        "warZone": storehouse.warZone.name,
        "company": storehouse.company.name,
        "linkName": storehouse.linkName,
        "linkPhone": storehouse.linkPhone,
        'runstate': storehouse.runState,
        'storehouseState': storehouse.storehouseState,
        'applytime': storeconnect.applyTime.strftime('%Y-%m-%d %H:%M:%S'),
    }
    logger_request.info(data)
    return JsonResponse(data)


def storeScreen(request, *args, **kwargs):
    """
        url    : /storehouse/screen/
        method : POST

    :param request:
            token: data.token, // 用户的秘钥
            page: data.page,
            maxItem: data.maxItem
            warZoneId: data.zone,//战区id
            companyid: data.company,//单位id
            runState:data.runState,//

            storehouseName:data.storehouseName,//搜索内容

    :return:
              'code': null, // 标志返回状态、0：成功 1：失败
              'msg': null, // 返回消息
              'totalNum':null,
              storehouselist:[{
                'storehouseId':null,//仓库id
                'storehouseName':null,//仓库名称
                'warZone':null,//所属战区
                'company':null,//所属单位
                'applytime':null,//申请时间              
                'storehouseState':null,//仓库状态 0：已开启，1：已关闭，
                'runstate':null,//0:在线，1:离线
                'connectstate':null,//0:已连接，1:已拒绝，2未连接
              }]         
    """
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    # pdb.set_trace()
    ##从数据库获取软件时的filter条件字典
    filterDict = {}
    user = datacheck.getUser(requestParam['token'])
    userType = user.userType

    if userType == '2':
        if requestParam['storehouseName'] != '':
            filterDict['storehouseName__icontains'] = requestParam['storehouseName']  # to do 关键字描述

        if requestParam['runState'] != '':
            if requestParam['runState'] == '0':
                filterDict['isRunning'] = True
                filterDict['runState'] = '0'

            elif requestParam['runState'] == '1':
                filterDict['isRunning'] = False
                filterDict['runState'] = '1'
            else:
                data = {
                    "code": 1,
                    "msg": "state Error",
                    'totalNum': 0,
                    'storehouselist': []
                }
                logger_request.info(data)
                return JsonResponse(data)

        if requestParam['connectstate'] != '':
            if requestParam['connectstate'] == '1':
                filterDict['connectState'] = 1

            elif requestParam['connectstate'] == '2':
                filterDict['connectState'] = 2
            else:
                data = {
                    "code": 1,
                    "msg": "connectState Error",
                    'totalNum': 0,
                    'storehouselist': []
                }
                logger_request.info(data)
                return JsonResponse(data)
        if requestParam['warZoneId'] != None:
            filterDict['warZone__id'] = requestParam['warZoneId']
            if requestParam['companyId'] != None:
                filterDict['company__id'] = requestParam['companyId']
                # pdb.set_trace()

        masterStorehouseList = Storehouse.objects.filter(user=user)
        masterStorehouse = masterStorehouseList[0]
        if masterStorehouse.isMasterStore == True:
            storeConnectList = StorehouseConnect.objects.filter(masterStorehouseId=masterStorehouse.id).filter(
                ~Q(connectState='3'))
            if storeConnectList.exists():
                # totalNum = len(storeConnectList)
                storeConnectLists = []

                storehouseLists = []

                for storeConnect in storeConnectList:
                    storehouseList = Storehouse.objects.filter(pk=storeConnect.subStorehouseId, **filterDict)

                    # result = storehouseList[min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
                    #                                                                                         requestParam['page'] *
                    #                                                                                         requestParam['maxItem'])]

                    for storehouse in storehouseList:
                        storehouseList = {
                            'storehouseId': storehouse.id,
                            'storehouseName': storehouse.storehouseName,
                            'storeIP': storehouse.storeIP,
                            'warZone': storehouse.warZone.name,
                            'company': storehouse.company.name,
                            'storehouseState': storehouse.storehouseState,
                            'runstate': storehouse.runState,
                            'connectstate': storehouse.connectState,
                            'applytime': storeConnect.applyTime.strftime('%Y-%m-%d %H:%M:%S'),
                        }
                        storehouseLists.append(storehouseList)
                    totalNum = len(storehouseLists)
                    result = storehouseLists[
                             min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
                                                                                                      requestParam[
                                                                                                          'page'] *
                                                                                                      requestParam[
                                                                                                          'maxItem'])]

            else:
                data = {
                    "code": 0,
                    "msg": "success",
                    "totalNum": 0,
                    "storehouselist": [],
                }
                logger_request.info(data)
                return JsonResponse(data)
        else:
            data = {
                "code": 0,
                "msg": "success",
                "totalNum": 0,
                "storehouselist": [],
            }
            logger_request.info(data)
            return JsonResponse(data)

    else:
        data = {
            'code': 1,
            'msg': 'userType error',
            "totalNum": 0,
            "storehouselist": [],
        }
        logger_request.info(data)
        return JsonResponse(data)

    # totalNum = len(storehouseLists)
    # result = storehouseLists[min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
    #                                                                                         requestParam['page'] *
    #                                                                                         requestParam['maxItem'])]

    data = {
        "code": 0,
        "msg": "success",
        "totalNum": totalNum,
        "storehouselist": result,
    }
    logger_request.info(data)
    return JsonResponse(data)


def warzoneGet(request, *args, **kwargs):
    """
        url    : /storehouse/warZoneList/
        method : POST

    :param request:
               token: data.token, // 用户的秘钥
               page: data.page,
               maxItem: data.maxItem

    :return:
                'code': null, // 标志返回状态、0：成功 1：失败
                'msg': null, // 返回消息
                'totalNum': null, // 总条数
                'warZonelist':[{
                    'warZoneId':null,//战区id
                    'warZoneState':null,//0:关闭 1：开启
                    'time':null,//创建时间
                    'name':null,//战区名称
                }]
    """

    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    # pdb.set_trace()    
    warZonelist = WarZone.objects.filter(isActive=True).order_by('-createTime')
    if warZonelist.exists():
        totalNum = len(warZonelist)
        warZonelists = []
        result = warZonelist[min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
                                                                                                      requestParam[
                                                                                                          'page'] *
                                                                                                      requestParam[
                                                                                                          'maxItem'])]

        for warzone in result:
            warZonelist = {
                'warZoneId': warzone.id,
                'warZoneState': warzone.warzoneState,
                'time': warzone.createTime.strftime('%Y-%m-%d %H:%M:%S'),
                'name': warzone.name,
            }
            warZonelists.append(warZonelist)

    else:

        data = {
            'code': 0,
            'msg': 'not exist',
            "totalNum": 0,
            "warZonelist": [],
        }
        logger_request.info(data)
        return JsonResponse(data)

    data = {
        "code": 0,
        "msg": "success",
        "totalNum": totalNum,
        "warZonelist": warZonelists,
    }
    logger_request.info(data)
    return JsonResponse(data)


def zoneOption(request, *args, **kwargs):
    """
        url    : /storehouse/warZoneOption/
        method : POST

    :param request:
            token: data.token, // 用户的秘钥
            name:data.name,//
            warZoneId:data.warZoneId,//
            zoneType:zoneType,//
            option:data.option,//0:删除，1：新增,2：修改

    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息

    """
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    # pdb.set_trace()    

    user = datacheck.getUser(requestParam['token'])
    userType = user.userType

    if userType == '2':
        if requestParam['option'] == '0':
            if requestParam['warZoneId'] != None:
                warzone = WarZone.objects.get(pk=requestParam['warZoneId'])
                warzone.isActive = False
                warzone.save()
            else:
                data = {
                    'code': 0,
                    'msg': 'warzone is None',
                }
                logger_request.info(data)
                return JsonResponse(data)
        elif requestParam['option'] == '1' and requestParam['name'] != '':
            warzone = WarZone.objects.create(
                name=requestParam['name'],
            )
        elif requestParam['option'] == '2':
            if requestParam['warZoneId'] != None:
                if requestParam['name'] != '' and requestParam['warZoneState'] == '':
                    warzone = WarZone.objects.get(pk=requestParam['warZoneId'])
                    warzone.name = requestParam['name']
                    warzone.save()
                elif requestParam['name'] == '' and requestParam['warZoneState'] != '':
                    warzone = WarZone.objects.get(pk=requestParam['warZoneId'])
                    warzone.warzoneState = requestParam['warZoneState']
                    warzone.save()
                elif requestParam['name'] != '' and requestParam['warZoneState'] != '':
                    warzone = WarZone.objects.get(pk=requestParam['warZoneId'])
                    warzone.name = requestParam['name']
                    warzone.warzoneState = requestParam['warZoneState']
                    warzone.save()
            else:
                data = {
                    'code': 0,
                    'msg': 'warZoneId is None',
                }
                logger_request.info(data)
                return JsonResponse(data)

    data = {
        "code": 0,
        "msg": "success",
    }
    logger_request.info(data)
    return JsonResponse(data)


def companyGet(request, *args, **kwargs):
    """
        url    : /storehouse/companyList/
        method : POST

    :param request:
               token: data.token, // 用户的秘钥
               page: data.page,
               maxItem: data.maxItem
               warZoneId:data.warZoneId,//''所有
    :return:
                'code': null, // 标志返回状态、0：成功 1：失败
                'msg': null, // 返回消息
                'totalNum': null, // 总条数
                'companyList':[{
                    'id':null,//id
                    'name':null,//
                    'state':null,//0：关闭，1：开启
                    'time':null,//创建时间
                    'isCompany':null,//0:战区 1：单位
                }]
    """

    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    # pdb.set_trace()    
    if requestParam['warZoneId'] != None:
        warZone = WarZone.objects.filter(pk=requestParam['warZoneId'])
        if warZone.exists():

            warZoneLists = []

            warZoneItem = warZone[0]
            warZoneList = {
                'id': warZoneItem.id,
                'name': warZoneItem.name,
                'state': warZoneItem.warzoneState,
                'time': warZoneItem.createTime.strftime('%Y-%m-%d %H:%M:%S'),
                'isCompany': '0',
            }
            warZoneLists.append(warZoneList)

            companylist = Company.objects.filter(warZone=warZoneItem).order_by('-createTime')

            if companylist.exists():
                totalNum = len(companylist) + 1
                companyLists = []
                for company in companylist:
                    companylist = {
                        'id': company.id,
                        'name': company.name,
                        'state': company.companyState,
                        'time': company.createTime.strftime('%Y-%m-%d %H:%M:%S'),
                        'isCompany': '1',
                    }
                    companyLists.append(companylist)

                Lists = warZoneLists + companyLists

            else:
                totalNum = 1

                Lists = warZoneLists

            # totalNum = len(companylist)+1

            result = Lists[min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
                                                                                                    requestParam[
                                                                                                        'page'] *
                                                                                                    requestParam[
                                                                                                        'maxItem'])]


        else:

            data = {
                'code': 0,
                'msg': 'not exist',
                "totalNum": 0,
                "companyList": [],
            }
            logger_request.info(data)
            return JsonResponse(data)


    elif requestParam['warZoneId'] == None:
        warZonelist = WarZone.objects.filter(isActive=True)
        # pdb.set_trace()
        if warZonelist.exists():

            warZoneTotal = len(warZonelist)

            # warZoneLists = []
            comLists = []
            for warZone in warZonelist:
                warZoneLists = []
                warZoneList = {
                    'id': warZone.id,
                    'name': warZone.name,
                    'state': warZone.warzoneState,
                    'time': warZone.createTime.strftime('%Y-%m-%d %H:%M:%S'),
                    'isCompany': '0',
                }
                warZoneLists.append(warZoneList)

                comLists += warZoneLists

                companylist = Company.objects.filter(warZone=warZone, isActive=True).order_by('-createTime')

                if companylist.exists():

                    companyLists = []
                    for company in companylist:
                        companylist = {
                            'id': company.id,
                            'name': company.name,
                            'state': company.companyState,
                            'time': company.createTime.strftime('%Y-%m-%d %H:%M:%S'),
                            'isCompany': '1',
                            'warZoneId': company.warZone.id
                        }
                        companyLists.append(companylist)

                    comLists += companyLists

            # else:
            #     totalNum = 1

            #     Lists = warZoneLists
            companyTotal = Company.objects.filter(isActive=True)
            comTotal = len(companyTotal)
            totalNum = comTotal + warZoneTotal
            # totalNum = len(companylist)+1

            result = comLists[min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
                                                                                                       requestParam[
                                                                                                           'page'] *
                                                                                                       requestParam[
                                                                                                           'maxItem'])]


        else:

            data = {
                'code': 0,
                'msg': 'not exist',
                "totalNum": 0,
                "companyList": [],
            }
            logger_request.info(data)
            return JsonResponse(data)

    data = {
        "code": 0,
        "msg": "success",
        "totalNum": totalNum,
        "companyList": result,
    }
    logger_request.info(data)
    return JsonResponse(data)


def companyOption(request, *args, **kwargs):
    """
        url    : /storehouse/companyOption/
        method : POST

    :param request:
            token: data.token, // 0,1,2
            name:data.name,//1,2
            id:data.id,//0,2
            warZoneId:data.warZoneId,//1,2
            stare:data.type,//2
            option:data.option,//0:删除，1：新增,2：修改

    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息

    """
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    # pdb.set_trace()    

    user = datacheck.getUser(requestParam['token'])
    userType = user.userType

    if userType == '2':
        if requestParam['option'] == '0':
            if requestParam['id'] != None:
                company = Company.objects.get(pk=requestParam['id'])
                company.isActive = False
                company.save()
            else:
                data = {
                    'code': 0,
                    'msg': 'company is None',
                }
                logger_request.info(data)
                return JsonResponse(data)
        elif requestParam['option'] == '1' and requestParam['name'] != '':
            warZone = WarZone.objects.get(pk=requestParam['warZoneId'])
            company = Company.objects.create(
                name=requestParam['name'],
                warZone=warZone
            )
        elif requestParam['option'] == '2':
            if requestParam['id'] != None:
                if requestParam['name'] != '' and requestParam['state'] == '' and requestParam['warZoneId'] == '':
                    company = Company.objects.get(pk=requestParam['id'])
                    company.name = requestParam['name']
                    company.save()
                elif requestParam['name'] == '' and requestParam['state'] != '' and requestParam['warZoneId'] == '':
                    company = Company.objects.get(pk=requestParam['id'])
                    company.companyState = requestParam['state']
                    company.save()
                elif requestParam['name'] != '' and requestParam['state'] != '' and requestParam['warZoneId'] == '':
                    company = Company.objects.get(pk=requestParam['id'])
                    company.name = requestParam['name']
                    company.companyState = requestParam['state']
                    company.save()
                elif requestParam['name'] != '' and requestParam['state'] != '' and requestParam['warZoneId'] != '':
                    # pdb.set_trace()
                    company = Company.objects.get(pk=requestParam['id'])
                    company.name = requestParam['name']
                    warZone = WarZone.objects.get(pk=requestParam['warZoneId'])
                    company.warZone = warZone
                    company.save()

            else:
                data = {
                    'code': 0,
                    'msg': 'id is None',
                }
                logger_request.info(data)
                return JsonResponse(data)

    data = {
        "code": 0,
        "msg": "success",
    }
    logger_request.info(data)
    return JsonResponse(data)
